import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import type { ICourse, ICourseCreateRequest, ICourseUpdateRequest, ICourseQueryParams } from '@/types/course/course';
import type { ICourseCategory, ICourseCategoryCreateRequest, ICourseCategoryUpdateRequest } from '@/types/course/courseCategory';
import { CourseStatusEnum, CourseCategoryStatusEnum } from '@/types/course/enums';
import { courseService, courseCategoryService } from '@/services/course';
import type { IAsyncState, IFilterState } from '@/types/common/base';

/**
 * 课程状态接口
 * @description 定义课程状态管理的完整接口
 */
export interface ICourseState {
  // 数据状态 - 课程
  /** 课程列表 */
  courses: ICourse[];
  /** 当前选中的课程 */
  selectedCourse: ICourse | null;
  /** 选中的课程ID列表（用于批量操作） */
  selectedCourseIds: string[];
  
  // 数据状态 - 课程分类
  /** 课程分类列表 */
  categories: ICourseCategory[];
  /** 当前选中的分类 */
  selectedCategory: ICourseCategory | null;
  /** 分类树结构 */
  categoryTree: any[];
  
  // 异步状态
  /** 课程异步操作状态 */
  courseAsync: IAsyncState;
  /** 分类异步操作状态 */
  categoryAsync: IAsyncState;
  
  // UI状态 - 课程
  /** 是否显示课程表单 */
  showCourseForm: boolean;
  /** 课程表单模式 */
  courseFormMode: 'create' | 'edit';
  /** 是否显示课程详情 */
  showCourseDetail: boolean;
  /** 是否显示课程批量操作面板 */
  showCourseBatchPanel: boolean;
  
  // UI状态 - 分类
  /** 是否显示分类表单 */
  showCategoryForm: boolean;
  /** 分类表单模式 */
  categoryFormMode: 'create' | 'edit';
  /** 是否显示分类管理面板 */
  showCategoryPanel: boolean;
  
  // 筛选状态
  /** 课程筛选条件 */
  courseFilters: IFilterState<{
    /** 分类ID筛选 */
    categoryId?: string;
    /** 教师筛选 */
    teacher?: string;
    /** 状态筛选 */
    status?: CourseStatusEnum;
    /** 难度等级筛选 */
    level?: 'beginner' | 'intermediate' | 'advanced';
    /** 标签筛选 */
    tags?: string[];
  }>;
  
  /** 分类筛选条件 */
  categoryFilters: IFilterState<{
    /** 父分类ID筛选 */
    parentId?: string;
    /** 状态筛选 */
    status?: CourseCategoryStatusEnum;
    /** 是否预设分类 */
    isPreset?: boolean;
  }>;
  
  // Actions - 课程数据操作
  /** 获取所有课程 */
  fetchCourses: (queryParams?: ICourseQueryParams) => Promise<void>;
  /** 添加课程 */
  addCourse: (courseData: ICourseCreateRequest) => Promise<void>;
  /** 更新课程 */
  updateCourse: (id: string, courseData: Omit<ICourseUpdateRequest, 'id'>) => Promise<void>;
  /** 删除课程 */
  deleteCourse: (id: string) => Promise<void>;
  /** 批量删除课程 */
  batchDeleteCourses: (ids: string[]) => Promise<void>;
  /** 搜索课程 */
  searchCourses: (keyword: string) => Promise<void>;
  
  // Actions - 分类数据操作
  /** 获取所有分类 */
  fetchCategories: () => Promise<void>;
  /** 获取分类树 */
  fetchCategoryTree: () => Promise<void>;
  /** 添加分类 */
  addCategory: (categoryData: ICourseCategoryCreateRequest) => Promise<void>;
  /** 更新分类 */
  updateCategory: (id: string, categoryData: Omit<ICourseCategoryUpdateRequest, 'id'>) => Promise<void>;
  /** 删除分类 */
  deleteCategory: (id: string) => Promise<void>;
  /** 初始化预设分类 */
  initializePresetCategories: () => Promise<void>;
  
  // Actions - 课程选择操作
  /** 选择课程 */
  selectCourse: (course: ICourse | null) => void;
  /** 切换课程选择状态 */
  toggleCourseSelection: (courseId: string) => void;
  /** 选择所有课程 */
  selectAllCourses: () => void;
  /** 清空课程选择 */
  clearCourseSelection: () => void;
  
  // Actions - 分类选择操作
  /** 选择分类 */
  selectCategory: (category: ICourseCategory | null) => void;
  
  // Actions - UI操作
  /** 设置课程表单显示状态 */
  setShowCourseForm: (show: boolean) => void;
  /** 设置课程表单模式 */
  setCourseFormMode: (mode: 'create' | 'edit') => void;
  /** 设置课程详情显示状态 */
  setShowCourseDetail: (show: boolean) => void;
  /** 设置课程批量操作面板显示状态 */
  setShowCourseBatchPanel: (show: boolean) => void;
  /** 设置分类表单显示状态 */
  setShowCategoryForm: (show: boolean) => void;
  /** 设置分类表单模式 */
  setCategoryFormMode: (mode: 'create' | 'edit') => void;
  /** 设置分类管理面板显示状态 */
  setShowCategoryPanel: (show: boolean) => void;
  
  // Actions - 筛选操作
  /** 更新课程筛选条件 */
  updateCourseFilters: (filters: Partial<ICourseState['courseFilters']['filters']>) => void;
  /** 设置课程搜索关键词 */
  setCourseSearchKeyword: (keyword: string) => void;
  /** 设置课程排序 */
  setCourseSorting: (sortBy: string, sortOrder: 'asc' | 'desc') => void;
  /** 重置课程筛选条件 */
  resetCourseFilters: () => void;
  /** 更新分类筛选条件 */
  updateCategoryFilters: (filters: Partial<ICourseState['categoryFilters']['filters']>) => void;
  /** 设置分类搜索关键词 */
  setCategorySearchKeyword: (keyword: string) => void;
  /** 重置分类筛选条件 */
  resetCategoryFilters: () => void;
  
  // Actions - 其他操作
  /** 重置状态 */
  reset: () => void;
  /** 刷新数据 */
  refresh: () => Promise<void>;
}

/**
 * 课程状态管理
 * @description 使用 Zustand 实现的课程和分类状态管理
 */
export const useCourseStore = create<ICourseState>()(
  devtools(
    persist(
      immer((set, get) => ({
        // 初始状态
        courses: [],
        selectedCourse: null,
        selectedCourseIds: [],
        categories: [],
        selectedCategory: null,
        categoryTree: [],
        courseAsync: {
          loading: false,
          error: null,
          lastUpdated: null
        },
        categoryAsync: {
          loading: false,
          error: null,
          lastUpdated: null
        },
        showCourseForm: false,
        courseFormMode: 'create',
        showCourseDetail: false,
        showCourseBatchPanel: false,
        showCategoryForm: false,
        categoryFormMode: 'create',
        showCategoryPanel: false,
        courseFilters: {
          filters: {},
          searchKeyword: '',
          sortBy: 'name',
          sortOrder: 'asc'
        },
        categoryFilters: {
          filters: {},
          searchKeyword: '',
          sortBy: 'name',
          sortOrder: 'asc'
        },

        // Actions 实现 - 课程数据操作
        fetchCourses: async (queryParams?: ICourseQueryParams) => {
          set((state) => {
            state.courseAsync.loading = true;
            state.courseAsync.error = null;
          });

          try {
            const result = await courseService.getAllCourses(queryParams);
            if (result.success) {
              set((state) => {
                state.courses = result.data;
                state.courseAsync.loading = false;
                state.courseAsync.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.courseAsync.loading = false;
                state.courseAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.courseAsync.loading = false;
              state.courseAsync.error = error instanceof Error ? error.message : '获取课程列表失败';
            });
          }
        },

        addCourse: async (courseData: ICourseCreateRequest) => {
          set((state) => {
            state.courseAsync.loading = true;
            state.courseAsync.error = null;
          });

          try {
            const result = await courseService.createCourse(courseData);
            if (result.success) {
              set((state) => {
                state.courses.push(result.data);
                state.courseAsync.loading = false;
                state.showCourseForm = false;
              });
            } else {
              set((state) => {
                state.courseAsync.loading = false;
                state.courseAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.courseAsync.loading = false;
              state.courseAsync.error = error instanceof Error ? error.message : '添加课程失败';
            });
            throw error;
          }
        },

        updateCourse: async (id: string, courseData: Omit<ICourseUpdateRequest, 'id'>) => {
          set((state) => {
            state.courseAsync.loading = true;
            state.courseAsync.error = null;
          });

          try {
            const result = await courseService.updateCourse(id, courseData);
            if (result.success) {
              set((state) => {
                const index = state.courses.findIndex(course => course.id === id);
                if (index !== -1) {
                  state.courses[index] = result.data;
                }
                if (state.selectedCourse?.id === id) {
                  state.selectedCourse = result.data;
                }
                state.courseAsync.loading = false;
                state.showCourseForm = false;
              });
            } else {
              set((state) => {
                state.courseAsync.loading = false;
                state.courseAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.courseAsync.loading = false;
              state.courseAsync.error = error instanceof Error ? error.message : '更新课程失败';
            });
            throw error;
          }
        },

        deleteCourse: async (id: string) => {
          try {
            const result = await courseService.deleteCourse(id);
            if (result.success) {
              set((state) => {
                state.courses = state.courses.filter(course => course.id !== id);
                if (state.selectedCourse?.id === id) {
                  state.selectedCourse = null;
                }
                state.selectedCourseIds = state.selectedCourseIds.filter(selectedId => selectedId !== id);
              });
            } else {
              set((state) => {
                state.courseAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.courseAsync.error = error instanceof Error ? error.message : '删除课程失败';
            });
            throw error;
          }
        },

        batchDeleteCourses: async (ids: string[]) => {
          set((state) => {
            state.courseAsync.loading = true;
            state.courseAsync.error = null;
          });

          try {
            const result = await courseService.batchDeleteCourses(ids);
            if (result.success) {
              set((state) => {
                state.courses = state.courses.filter(course => !ids.includes(course.id));
                if (state.selectedCourse && ids.includes(state.selectedCourse.id)) {
                  state.selectedCourse = null;
                }
                state.selectedCourseIds = state.selectedCourseIds.filter(selectedId => !ids.includes(selectedId));
                state.courseAsync.loading = false;
                state.showCourseBatchPanel = false;
              });
            } else {
              set((state) => {
                state.courseAsync.loading = false;
                state.courseAsync.error = result.error || '批量删除失败';
              });
            }
          } catch (error) {
            set((state) => {
              state.courseAsync.loading = false;
              state.courseAsync.error = error instanceof Error ? error.message : '批量删除课程失败';
            });
            throw error;
          }
        },

        searchCourses: async (keyword: string) => {
          set((state) => {
            state.courseAsync.loading = true;
            state.courseAsync.error = null;
          });

          try {
            const result = await courseService.searchCourses(keyword);
            if (result.success) {
              set((state) => {
                state.courses = result.data;
                state.courseAsync.loading = false;
                state.courseAsync.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.courseAsync.loading = false;
                state.courseAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.courseAsync.loading = false;
              state.courseAsync.error = error instanceof Error ? error.message : '搜索课程失败';
            });
          }
        },

        // Actions 实现 - 分类数据操作
        fetchCategories: async () => {
          set((state) => {
            state.categoryAsync.loading = true;
            state.categoryAsync.error = null;
          });

          try {
            const result = await courseCategoryService.getAllCategories();
            if (result.success) {
              set((state) => {
                state.categories = result.data;
                state.categoryAsync.loading = false;
                state.categoryAsync.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.categoryAsync.loading = false;
                state.categoryAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.categoryAsync.loading = false;
              state.categoryAsync.error = error instanceof Error ? error.message : '获取分类列表失败';
            });
          }
        },

        fetchCategoryTree: async () => {
          set((state) => {
            state.categoryAsync.loading = true;
            state.categoryAsync.error = null;
          });

          try {
            const result = await courseCategoryService.getCategoryTree();
            if (result.success) {
              set((state) => {
                state.categoryTree = result.data;
                state.categoryAsync.loading = false;
                state.categoryAsync.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.categoryAsync.loading = false;
                state.categoryAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.categoryAsync.loading = false;
              state.categoryAsync.error = error instanceof Error ? error.message : '获取分类树失败';
            });
          }
        },

        addCategory: async (categoryData: ICourseCategoryCreateRequest) => {
          set((state) => {
            state.categoryAsync.loading = true;
            state.categoryAsync.error = null;
          });

          try {
            const result = await courseCategoryService.createCategory(categoryData);
            if (result.success) {
              set((state) => {
                state.categories.push(result.data);
                state.categoryAsync.loading = false;
                state.showCategoryForm = false;
              });
              // 重新获取分类树
              get().fetchCategoryTree();
            } else {
              set((state) => {
                state.categoryAsync.loading = false;
                state.categoryAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.categoryAsync.loading = false;
              state.categoryAsync.error = error instanceof Error ? error.message : '添加分类失败';
            });
            throw error;
          }
        },

        updateCategory: async (id: string, categoryData: Omit<ICourseCategoryUpdateRequest, 'id'>) => {
          set((state) => {
            state.categoryAsync.loading = true;
            state.categoryAsync.error = null;
          });

          try {
            const result = await courseCategoryService.updateCategory(id, categoryData);
            if (result.success) {
              set((state) => {
                const index = state.categories.findIndex(category => category.id === id);
                if (index !== -1) {
                  state.categories[index] = result.data;
                }
                if (state.selectedCategory?.id === id) {
                  state.selectedCategory = result.data;
                }
                state.categoryAsync.loading = false;
                state.showCategoryForm = false;
              });
              // 重新获取分类树
              get().fetchCategoryTree();
            } else {
              set((state) => {
                state.categoryAsync.loading = false;
                state.categoryAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.categoryAsync.loading = false;
              state.categoryAsync.error = error instanceof Error ? error.message : '更新分类失败';
            });
            throw error;
          }
        },

        deleteCategory: async (id: string) => {
          try {
            const result = await courseCategoryService.deleteCategory(id);
            if (result.success) {
              set((state) => {
                state.categories = state.categories.filter(category => category.id !== id);
                if (state.selectedCategory?.id === id) {
                  state.selectedCategory = null;
                }
              });
              // 重新获取分类树
              get().fetchCategoryTree();
            } else {
              set((state) => {
                state.categoryAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.categoryAsync.error = error instanceof Error ? error.message : '删除分类失败';
            });
            throw error;
          }
        },

        initializePresetCategories: async () => {
          set((state) => {
            state.categoryAsync.loading = true;
            state.categoryAsync.error = null;
          });

          try {
            const result = await courseCategoryService.initializePresetCategories();
            if (result.success) {
              set((state) => {
                // 将新创建的预设分类添加到列表中
                state.categories.push(...result.data);
                state.categoryAsync.loading = false;
              });
              // 重新获取完整的分类列表和树结构
              get().fetchCategories();
              get().fetchCategoryTree();
            } else {
              set((state) => {
                state.categoryAsync.loading = false;
                state.categoryAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.categoryAsync.loading = false;
              state.categoryAsync.error = error instanceof Error ? error.message : '初始化预设分类失败';
            });
          }
        },

        // Actions 实现 - 课程选择操作
        selectCourse: (course: ICourse | null) => {
          set((state) => {
            state.selectedCourse = course;
          });
        },

        toggleCourseSelection: (courseId: string) => {
          set((state) => {
            const index = state.selectedCourseIds.indexOf(courseId);
            if (index > -1) {
              state.selectedCourseIds.splice(index, 1);
            } else {
              state.selectedCourseIds.push(courseId);
            }
          });
        },

        selectAllCourses: () => {
          set((state) => {
            state.selectedCourseIds = state.courses.map(course => course.id);
          });
        },

        clearCourseSelection: () => {
          set((state) => {
            state.selectedCourseIds = [];
            state.selectedCourse = null;
          });
        },

        // Actions 实现 - 分类选择操作
        selectCategory: (category: ICourseCategory | null) => {
          set((state) => {
            state.selectedCategory = category;
          });
        },

        // Actions 实现 - UI操作
        setShowCourseForm: (show: boolean) => {
          set((state) => {
            state.showCourseForm = show;
            if (!show) {
              state.selectedCourse = null;
            }
          });
        },

        setCourseFormMode: (mode: 'create' | 'edit') => {
          set((state) => {
            state.courseFormMode = mode;
          });
        },

        setShowCourseDetail: (show: boolean) => {
          set((state) => {
            state.showCourseDetail = show;
          });
        },

        setShowCourseBatchPanel: (show: boolean) => {
          set((state) => {
            state.showCourseBatchPanel = show;
          });
        },

        setShowCategoryForm: (show: boolean) => {
          set((state) => {
            state.showCategoryForm = show;
            if (!show) {
              state.selectedCategory = null;
            }
          });
        },

        setCategoryFormMode: (mode: 'create' | 'edit') => {
          set((state) => {
            state.categoryFormMode = mode;
          });
        },

        setShowCategoryPanel: (show: boolean) => {
          set((state) => {
            state.showCategoryPanel = show;
          });
        },

        // Actions 实现 - 筛选操作
        updateCourseFilters: (filters: Partial<ICourseState['courseFilters']['filters']>) => {
          set((state) => {
            state.courseFilters.filters = { ...state.courseFilters.filters, ...filters };
          });
        },

        setCourseSearchKeyword: (keyword: string) => {
          set((state) => {
            state.courseFilters.searchKeyword = keyword;
          });
        },

        setCourseSorting: (sortBy: string, sortOrder: 'asc' | 'desc') => {
          set((state) => {
            state.courseFilters.sortBy = sortBy;
            state.courseFilters.sortOrder = sortOrder;
          });
        },

        resetCourseFilters: () => {
          set((state) => {
            state.courseFilters = {
              filters: {},
              searchKeyword: '',
              sortBy: 'name',
              sortOrder: 'asc'
            };
          });
        },

        updateCategoryFilters: (filters: Partial<ICourseState['categoryFilters']['filters']>) => {
          set((state) => {
            state.categoryFilters.filters = { ...state.categoryFilters.filters, ...filters };
          });
        },

        setCategorySearchKeyword: (keyword: string) => {
          set((state) => {
            state.categoryFilters.searchKeyword = keyword;
          });
        },

        resetCategoryFilters: () => {
          set((state) => {
            state.categoryFilters = {
              filters: {},
              searchKeyword: '',
              sortBy: 'name',
              sortOrder: 'asc'
            };
          });
        },

        // Actions 实现 - 其他操作
        reset: () => {
          set((state) => {
            state.courses = [];
            state.selectedCourse = null;
            state.selectedCourseIds = [];
            state.categories = [];
            state.selectedCategory = null;
            state.categoryTree = [];
            state.courseAsync = {
              loading: false,
              error: null,
              lastUpdated: null
            };
            state.categoryAsync = {
              loading: false,
              error: null,
              lastUpdated: null
            };
            state.showCourseForm = false;
            state.courseFormMode = 'create';
            state.showCourseDetail = false;
            state.showCourseBatchPanel = false;
            state.showCategoryForm = false;
            state.categoryFormMode = 'create';
            state.showCategoryPanel = false;
            state.courseFilters = {
              filters: {},
              searchKeyword: '',
              sortBy: 'name',
              sortOrder: 'asc'
            };
            state.categoryFilters = {
              filters: {},
              searchKeyword: '',
              sortBy: 'name',
              sortOrder: 'asc'
            };
          });
        },

        refresh: async () => {
          const { fetchCourses, fetchCategories, fetchCategoryTree } = get();
          await Promise.all([
            fetchCourses(),
            fetchCategories(),
            fetchCategoryTree()
          ]);
        }
      })),
      {
        name: 'course-store',
        partialize: (state) => ({
          courses: state.courses,
          categories: state.categories,
          courseFilters: state.courseFilters,
          categoryFilters: state.categoryFilters
        })
      }
    ),
    {
      name: 'course-store'
    }
  )
);